package com.micro.service.dao;

import com.micro.service.model.UserInfo;
import org.apache.ibatis.annotations.*;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * Create by Vic Xu on 2019/3/6
 */
public interface UserInfoDao {

    @Select("select * from user_info")
    List<UserInfo> getAllUserInfo();

    @Select("select * from user_info where id=#{id}")
    UserInfo getUserInfoById(String id);

    @Insert("insert into user_info(id,name,age,sex,mail,createDate) values(#{id},#{name},#{age},#{sex},#{mail},#{createDate})")
    @Options(keyColumn = "id")
    int saveUser(UserInfo userInfo);

    @InsertProvider(type = UserInfoDaoProvider.class ,method = "insertAll")
    int batchSaveUser(@Param("userList") List<UserInfo> userInfos);

    @Update("update user_info set name=#{name},age=#{age},sex=#{sex},mail=#{mail} where id=#{id}")
    int updateUser(UserInfo userInfo);

    @Delete("delete from user_info where id=#{id}")
    int deleteUser(String id);

    class UserInfoDaoProvider {

        public String insertAll(Map map) {
            List<UserInfo> userInfos = (List<UserInfo>) map.get("userList");
            StringBuilder sb = new StringBuilder();
            sb.append("insert into user_info(id,name,age,sex,mail,createDate) values");
            MessageFormat mf = new MessageFormat("(#'{'userList[{0}].id},#'{'userList[{0}].name},#'{'userList[{0}].age},#'{'userList[{0}].sex},#'{'userList[{0}].mail},#'{'userList[{0}].createDate})");
            for (int i = 0; i < userInfos.size(); i++) {
                sb.append(mf.format(new Object[] {i}));
                if (i < userInfos.size() -1)
                    sb.append(",");
            }
            return sb.toString();
        }
    }

}
